package com.pluszg.nutrition.common.utils.json.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.pluszg.nutrition.common.utils.DateUtil;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;

public class DateSerializer extends StdSerializer<Date> {

    private final String pattern;

    public DateSerializer(String pattern) {
        super(Date.class);
        this.pattern = pattern;
    }

    @Override
    public void serialize(Date value, JsonGenerator generator, SerializerProvider serializers) throws IOException {
        if (Objects.isNull(value)) {
            generator.writeNull();
        } else {
            generator.writeString(DateUtil.format(value, pattern));
        }
    }
}